package com.app.couponsharelife.ui.main.home.topic
import android.content.Intent
import android.graphics.Paint
import android.graphics.drawable.AnimationDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.BaseActivity
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.DataUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_topic_hdk.*
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.base_title_white.*
import kotlinx.android.synthetic.main.rvitem_topic_hdk.view.*
import java.text.DecimalFormat
import java.util.HashMap
/**
 *Created by xct on 2019/5/8
 *Description:好单库好货专场
 */
class TopicHDKActivity:BaseActivity() {
    private var pageIndex=1
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    private var adapter: MyAdapter?=null
    private var favoritesID=""
    private var name=""
    private var imagUrl=""
    override val viewLayoutId: Int
        get() = R.layout.activity_topic_hdk
    override fun initViews() {
        AppUtils.initImmersionBar(this,true)
        favoritesID=intent.getStringExtra("FavoritesID")
        name=intent.getStringExtra("Name")?:""
        imagUrl=intent.getStringExtra("ImagUrl")?:""
        basetitle_title.text=name
        Glide.with(this).asBitmap()
                .apply(RequestOptions().error(R.drawable.ic_app_place_holder2))
                .load(imagUrl)
                .into(topicHDK_ivBanner)
        basetitle_llclose.setOnClickListener { finish() }
        setRefresh()
        topicHDK_rv.layoutManager=LinearLayoutManager(this)
        adapter=MyAdapter()
        topicHDK_rv.adapter=adapter
        getGoodsList(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        topicHDK_smart.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }
            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }
            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }
            override fun loadMore() {
                getGoodsList(false)
            }
            override fun refresh() {
                //pageIndex=1
                getGoodsList(true)
            }

        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun getGoodsList(isRefresh:Boolean){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        map["id"]=favoritesID
        RetrofitWorker.retrofitWorker.getTopicGoodList(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().hdkData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<HDKGoodsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HDKGoodsBean>) {
                        dismissProgressDialog()
                        if (isRefresh){
                            topicHDK_smart.finishRefresh()
                        }
                        if (it.code==200&&it.data!=null){
                            if (it.data!!.data!!.isNotEmpty()){
                                topicHDK_llerror.visibility=View.GONE
                                topicHDK_rv.visibility=View.VISIBLE
                                goodsList.clear()
                                goodsList.addAll(it.data!!.datas)
                                topicHDK_smart.finishLoadMoreWithNoMoreData()
                                adapter!!.notifyDataSetChanged()
                            }else{
                                topicHDK_llerror.visibility=View.VISIBLE
                                topicHDK_rv.visibility=View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        topicHDK_llerror.visibility=View.VISIBLE
                        topicHDK_rv.visibility=View.GONE
                        if (isRefresh){
                            topicHDK_smart.finishRefresh()
                        }
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                            //Log.e("eeee",e.toString())
                        }
                    }

                })    }

    override fun onDestroy() {
        super.onDestroy()
        AppUtils.destroyImmersionBar(this)
    }
    private inner class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.rvitem_topic_hdk,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return goodsList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (goodsList.isNotEmpty()) {
                if (holder is MyHolder) {
                    val good=goodsList[position]
                    val df = DecimalFormat("#0.00")
                    Glide.with(holder.itemView).asBitmap()
                            .apply(RequestOptions().transforms(CenterCrop(), RoundedCorners( 5))
                                    .placeholder(R.drawable.ic_good_place_holder).error(R.drawable.ic_good_place_holder))
                            .load(good.pict_url)
                            .into(holder.goodsImag!!)
                    holder.goodsTitle!!.text =good.title
                    //holder.goods.setImageResource(good.userType)
                    holder.goodsXLNumber!!.text = good.volume
                    holder.goodsPrice!!.text = df.format(good.final_price.toDouble())
                    holder.goodsFL!!.text = String.format("约返¥%s", df.format(good.vip_commission.toDouble()))
                    holder.goodsOldPriceType!!.text=good.goodsSource+"价"
                    holder.goodsOldPrice!!.text=good.original_price
                    holder.goodsDayXLNumber!!.text=good.todaysale
                    holder.goodsOldPrice!!.paint.flags= Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
                    if (good.has_coupon) {
                        holder.goodsYHQPrice!!.text = String.format("¥%s", good.coupon_price)
                        holder.goodsYHQBG!!.visibility = View.VISIBLE
                    } else {
                        holder.goodsYHQBG!!.visibility = View.GONE
                    }
                    holder.itemView.setOnClickListener {
                        val intent = Intent(this@TopicHDKActivity, GoodDetailActivity::class.java)
                        intent.putExtra("good", good)
                        startActivity(intent)
                    }
                }
            }
        }
    }
    private inner class MyHolder(itemview: View): RecyclerView.ViewHolder(itemview){
        var goodsImag:ImageView?=null
        var goodsTitle:TextView?=null
        var goodsPrice:TextView?=null
        var goodsOldPrice:TextView?=null
        var goodsOldPriceType:TextView?=null
        var goodsFL:TextView?=null
        var goodsYHQPrice:TextView?=null
        var goodsXLNumber:TextView?=null
        var goodsDayXLNumber:TextView?=null
        var goodsYHQBG: LinearLayout?=null
        init {
            goodsImag=itemView.ivGoods
            goodsTitle=itemView.tvGoodsName
            goodsPrice=itemView.tvGoodPrice
            goodsOldPrice=itemView.tvGoodSvipProfit
            goodsOldPriceType=itemView.tvGoodtype
            goodsFL=itemView.tvGoodVipProfit
            goodsYHQPrice=itemView.tvCouponAmount
            goodsXLNumber=itemView.tvGoodVolume
            goodsDayXLNumber=itemView.tvDaySellNumber
            goodsYHQBG=itemView.choiceness_rvitm_llq1
        }
    }
}